<template>
    <div class="layout">
        <div v-if="!isLoading && !isTableList" class="no-data-box">
            <div class="title-box">
                <img
                    class="title-img"
                    src="//img.static-keyid.cn/toolspace/scrm/2023/08/1691736214883deyyykgjvwfrbi4v.png" />
                <div class="title-content">
                    <div class="title-name">分流码</div>
                    <div class="title-desc">
                        企业在后台设置不同引流分组对应的客户活码，可在包裹卡、海报等场景上，仅凭同一个二维码或链接将客户分配至设定好的不同引流客服，有效提升企业工作效率，降低企业成本。
                    </div>
                    <el-button class="title-button" type="primary" @click="onOpenUse">去使用</el-button>
                </div>
            </div>
            <div class="scene-box">
                <div class="scene-box-title">营销场景</div>
                <div class="scene-box-img">
                    <img
                        class="scene-img"
                        src="//img.static-keyid.cn/toolspace/scrm/2023/08/1693215845819w7w9eauttnx6hi29.png" />
                </div>
            </div>
        </div>
        <div v-show="!isLoading && isTableList" class="container">
            <div class="container-form">
                <ZwSearchForm row-num="4" default-expand :option="searchOption" @search="search" @reset="reset" />
            </div>
            <div class="container-table">
                <div class="container-table-account">
                    <ShareAccountConfiguration
                        ref="shareAccountConfigurationRef"
                        :is-show-mini-app="false"
                        :type="13"
                        :no-need-loading="true"
                        @auth="fissionAuth" />
                    <el-button type="primary" @click="onOpenNew">新建活动</el-button>
                </div>
                <ZwTable
                    ref="tableRef"
                    class="table-box"
                    tab-h="initial"
                    :fetch-api="fetchApi()"
                    :row-key="getRowKey"
                    :close-loading="true"
                    :option="tableOption"
                    :fetch-params="state.searchParams"
                    @updateData="getTableData">
                </ZwTable>
            </div>
        </div>
        <PlugDialog v-model="plugShow" :base-info="plugInfo" />
    </div>
</template>
<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
import ZwTable from '@/components/zw/table1.0/Table';
import ShareAccountConfiguration from '@/components/common/ShareAccountConfiguration.vue';
import PlugDialog from './PlugDialog.vue';

import { ref, reactive, computed, onMounted, markRaw } from 'vue';
import { useRouter } from 'vue-router';

import { WarningFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCreateList } from '@/api/common';

import { deepCopy } from '@/utils/helper';

import { shuntCodeList, shuntCodeEnd, shuntCodeDel } from '@/api/smartMarketing/drainage/shuntCode';

const router = useRouter();

const tableRef: any = ref<HTMLElement | null>(null);

const isLoading = ref<boolean>(true);
const isTableList = ref<boolean>(false);
const isTableSearch = ref<boolean>(false);

const authInfo = ref<any>({});

const shareAccountConfigurationRef = ref<any>(null);

/**
 * 推广弹框：true-展示 false-关闭
 */
const plugShow = ref<boolean>(false);

/**
 * 推广弹框：活动信息
 */
const plugInfo = ref<any>({});

/**
 * 状态颜色
 */
const StatusColorOption = {
    未开始: '#EAEAEA',
    进行中: '#2FB6E4',
    已结束: '#F14144'
};

const defaultParams = {
    activity_name: '', // 活动名称
    create_uid: [], //创建人
    activity_status: '' //活动状态
};

const state = reactive({
    searchParams: deepCopy(defaultParams)
});

const searchOption = computed(() => {
    return [
        {
            label: '活动名称',
            name: 'activity_name',
            value: '',
            type: 'input',
            placeholder: '请输入活动名称'
        },
        {
            label: '活动状态',
            name: 'activity_status',
            value: '',
            type: 'select',
            placeholder: '请选择活动状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '未开始', id: 1 },
                        { name: '进行中', id: 2 },
                        { name: '已结束', id: 3 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建人',
            name: 'created_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});

const search = (v: any) => {
    isTableSearch.value = true;
    state.searchParams = deepCopy({ ...v, activity_name: v.activity_name?.trim() });
};
const reset = (v: any) => {
    isTableSearch.value = true;
    state.searchParams = deepCopy(v);
};

const tableOption = [
    {
        prop: 'activity_name',
        label: '活动名称',
        showOverflowTooltip: true,
        minWidth: 200
    },
    {
        prop: 'group_num',
        label: '引流分组',
        showOverflowTooltip: true,
        width: 180
    },
    {
        prop: 'status_name',
        label: '活动状态',
        width: 180,
        render({ row }: any) {
            return (
                <div
                    class="activity-status"
                    style={{
                        '--status-bgcolor': StatusColorOption[row.status_name] ?? '#2FB6E4'
                    }}>
                    {row.status_name}
                </div>
            );
        }
    },
    {
        prop: 'period_type',
        label: '活动有效期',
        width: 300,
        render({ row }: any) {
            return (
                <div class="period_type">
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            <span>{row.begin_date}</span>
                            <span> - </span>
                            <span>{row.end_date}</span>
                        </div>
                    )}
                </div>
            );
        }
    },
    {
        prop: 'created_user',
        label: '创建人',
        showOverflowTooltip: true,
        width: 180
    },
    {
        prop: 'updated_at',
        label: '更新时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        width: 210,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '编辑',
                authCode: 'EDIT',
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status),
                click: (row: any) => onEdit(row)
            },
            {
                name: '查看',
                authCode: 'LOOK',
                click: (row: any) => onLook(row)
            },
            {
                name: '结束',
                authCode: 'END_CODE',
                isRender: ({ row }: any) => [2].includes(row.activity_status),
                click: (row: any) => onEnd(row)
            },
            {
                name: '数据',
                authCode: 'STATISTICS',
                isRender: ({ row }: any) => [2, 3].includes(row.activity_status),
                click: (row: any) => onRecord(row)
            },
            {
                name: '删除',
                authCode: 'DEL_CODE',
                isRender: ({ row }: any) => [1, 3].includes(row.activity_status),
                click: (row: any) => onDelete(row)
            },
            {
                name: '推广',
                authCode: 'PLUG',
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status),
                click: (row: any) => onPopularize(row)
            }
        ]
    }
];
/**
 * key
 */
const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = () => {
    return shuntCodeList;
};

/**
 * 获取列表数据
 * @param list table数据
 */
const getTableData = (list?: any) => {
    isLoading.value = false;
    if (!isTableSearch.value && !list.length) {
        isTableList.value = false;
    } else {
        isTableList.value = true;
    }
};

/**
 * 去使用
 */
const onOpenUse = async () => {
    if (!(await onCheck())) return;
    // isTableList.value = true;
    onDetail('new');
};

/**
 * 新建活动
 */
const onOpenNew = async () => {
    if (!(await onCheck())) return;
    onDetail('new');
};

/**
 * 编辑
 */
const onEdit = (val: any) => {
    onDetail('edit', val);
};

/**
 * 查看
 */
const onLook = (val: any) => {
    onDetail('look', val);
};

/**
 * 删除
 */
const onDelete = async (val: any) => {
    await ElMessageBox.confirm('确定要删除此活动吗？', '提示', {
        customClass: 'shunt-code-msg-box-confirm',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(WarningFilled)
    });
    await shuntCodeDel({ id: val.id });
    tableRef.value.reload();
    ElMessage.success('删除成功');
};

/**
 * 推广
 */
const onPopularize = async (val: any) => {
    plugInfo.value = val;
    plugShow.value = true;
};

/**
 * 结束
 */
const onEnd = async (val: any) => {
    await ElMessageBox.confirm('确定要提前结束此活动吗？', '提示', {
        customClass: 'shunt-code-msg-box-confirm',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(WarningFilled)
    });
    await shuntCodeEnd({ id: val.id });
    tableRef.value.reload();
    ElMessage.success('提前结束成功');
};

/**
 * 数据
 */
const onRecord = (val: any) => {
    router.push({ path: '/smartMarketing/drainage/shuntCode/dataStatistics', query: { id: val.id } });
};

/**
 * 前往详情页
 * @param type new-新建, edit-编辑, look-查看
 * @param val 活动数据
 */
const onDetail = (type: string, val: any = {}) => {
    router.push({
        path: '/smartMarketing/drainage/shuntCode/detail',
        query: { type: type, id: val.id }
    });
};

// 获取配置权限
const fissionAuth = (val: any) => {
    !!val && (authInfo.value = val);
};

/**
 * 校验
 */
const onCheck = async () => {
    // 是否配置公众号
    if (!authInfo.value.official_account_id || authInfo.value.is_set_official != 2) {
        await ElMessageBox.confirm('此功能需要使用公众号，请先配置公众号', '提示', {
            customClass: 'shunt-code-msg-box-confirm',
            confirmButtonText: '去配置',
            cancelButtonText: '取消',
            type: 'warning',
            icon: markRaw(WarningFilled)
        });
        shareAccountConfigurationRef.value.configurationOfficialAccounts();
        return false;
    }
    return true;
};

onMounted(() => {});
</script>
<style lang="scss" scoped>
.layout {
    .no-data-box {
        .title-box {
            display: flex;
            padding: 16px 16px 16px 24px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            background-color: #fff;

            .title-img {
                margin-right: 16px;
                min-width: 101px;
                height: 101px;
            }

            .title-content {
                .title-name {
                    font-size: 20px;
                    font-family: PingFangSC-Medium, 'PingFang SC';
                    font-weight: 500;
                    color: #33302d;
                    line-height: 28px;
                }

                .title-desc {
                    padding-top: 4px;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, 'PingFang SC';
                    font-weight: 400;
                    color: #33302d;
                    line-height: 20px;
                }

                .title-button {
                    margin-top: 16px;
                }
            }
        }

        .scene-box {
            margin-top: 16px;
            padding: 24px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            background-color: #fff;

            .scene-box-title {
                display: flex;
                align-items: center;
                font-size: 16px;
                font-family: PingFangSC-Medium, 'PingFang SC';
                font-weight: 500;
                color: #333;
                line-height: 16px;

                &::before {
                    width: 3px;
                    height: 16px;
                    margin-right: 6px;
                    content: '';
                    border-radius: 2px;
                    background-color: #ff6b00;
                }
            }

            .scene-box-img {
                margin: 30px 16px 20px;
                max-width: 1332px;
            }

            .scene-img {
                width: 100%;
                height: 100%;
            }
        }
    }

    .container {
        height: calc(100vh - 142px);
        display: flex;
        flex-direction: column;

        .container-form {
            border: 1px solid #eaeaea;
        }

        .container-table {
            display: flex;
            flex-direction: column;
            overflow: hidden;
            box-sizing: border-box;
            border: 1px solid #eaeaea;
            background-color: #fff;
            padding: 16px;
            margin-top: 16px;
            flex: 1;

            .zw-table {
                display: flex;
                flex-direction: column;
                flex: 1;
                overflow: hidden;

                :deep(.el-table) {
                    flex: 1;

                    .el-table__empty-block {
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                    }
                }
            }

            .container-table-account {
                display: flex;
                justify-content: space-between;
            }
        }
    }

    :deep(.activity-status) {
        --status-bgcolor: #2fb6e4;

        &::before {
            content: '';
            display: inline-block;
            width: 8px;
            height: 8px;
            margin-right: 8px;
            background-color: var(--status-bgcolor);
            border-radius: 4px;
        }
    }

    :deep(.period_type) {
        height: 46px;
        display: flex;
        align-items: center;
    }

    :deep(.zw-table__com_table.el-table .el-table__body tbody tr td) {
        padding: 8.5px 0;
    }
}
</style>
<style lang="scss">
.shunt-code-msg-box-confirm {
    width: 400px;

    .el-message-box__content {
        padding: 0;
    }

    .el-message-box__container {
        margin: 42px 25px 44px;
        display: flex;
        justify-content: center;
        align-items: center;

        .el-icon {
            position: relative;
            top: 0;
            transform: translateY(0);

            --el-messagebox-color: #faad14;
        }
    }

    .el-message-box__message {
        padding: 0 0 0 8px;
    }

    .el-button--primary {
        background-color: var(--el-button-bg-color) !important;
    }
}
</style>
